// 初始化数据库
const db = wx.cloud.database();
const uimg = db.collection("uimg");

// import { request } from "../../request/request";
import { swiperImg } from "../../static/js/loveData";

// 获取应用实例
const app = getApp();

//Page Object
Page({
  data: {
    theme: app.globalData.theme,
    time: "",
    showNotice: null,
    swiperList: [],
    swiperImg,
    fileID: "",
    myInterval: null,
    o_openid: "",

    myAvatarUrl: "",
    myNickname: "",
    otherAvatarUrl: "",
    otherNickname: "",

    navHeight: app.globalData.navBarHeight,
    menuHeight: app.globalData.menuHeight,
    menuRight: app.globalData.menuRight,
    menuTop: app.globalData.menuTop,
  },

  setLoveTime() {
    const { o_openid } = this.data;
    if (o_openid == "") {
      wx.showModal({
        title: "绑定提醒",
        content: "你还没有绑定情侣，是否现在绑定？",
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/packageMine/pages/invitecode/invitecode",
            });
          }
        },
      });
    } else {
      wx.navigateTo({
        url: "/packageOther/pages/settime/settime",
      });
    }
  },

  // 获取时间
  getLoveTime(openid) {
    const that = this;
    wx.showLoading({
      title: "Loading...",
      mask: true,
    });
    uimg.where({ _openid: openid }).get({
      success: (res) => {
        that.setData({
          myAvatarUrl: res.data[0].avatarUrl,
          myNickname: res.data[0].nickname,
        });
        if (res.data[0].love_time) {
          app.globalData.loveTime = res.data[0].love_time;
          wx.setStorageSync("love_time", res.data[0].love_time);
          that.startInterval();
        } else {
          that.setData({
            time: "",
          });
        }

        if (res.data[0].o_openid) {
          uimg.where({ _openid: res.data[0].o_openid }).get({
            success: (ret) => {
              that.setData({
                otherAvatarUrl: ret.data[0].avatarUrl,
                otherNickname: ret.data[0].nickname,
              });
            },
          });
        }
      },
      fail: (err) => {
        wx.showModal({
          title: "错误",
          content: err,
          showCancel: true,
          cancelText: "取消",
          cancelColor: "#000000",
          confirmText: "确定",
          confirmColor: "#a5646d",
        });
      },
      complete: () => {
        wx.hideLoading();
      },
    });
  },

  // 时间计算
  countDown(loveTime) {
    var inputTime = +new Date(loveTime);
    var nowTime = +new Date();
    var times = (nowTime - inputTime) / 1000;
    var d = parseInt(times / 60 / 60 / 24);
    d = d < 10 ? "0" + d : d;
    var h = parseInt((times / 60 / 60) % 24);
    h = h < 10 ? "0" + h : h;
    var m = parseInt((times / 60) % 60);
    m = m < 10 ? "0" + m : m;
    var s = parseInt(times % 60);
    s = s < 10 ? "0" + s : s;
    // this.setData({
    //   time: `相恋：${d}天 ${h}小时${m}分${s}秒`,
    // });
    return `相恋：${d}天 ${h}小时${m}分${s}秒`;
  },

  // 开启定时器
  startInterval() {
    const that = this;
    let { myInterval } = that.data;
    // const loveTime = wx.getStorageSync("love_time");
    const loveTime = app.globalData.loveTime;
    myInterval = setInterval(() => {
      const test = that.countDown(loveTime);
      that.setData({
        time: test,
      });
    }, 1000);
    that.setData({ myInterval });
  },

  // 获取轮播图片
  getImgsData(openid, imgurl, fileId) {
    const that = this;

    uimg.where({ _openid: openid }).get({
      success: (res) => {
        that.setData({
          swiperList: res.data[0].mySwiper,
        });
      },
      fail: () => {
        wx.showToast({
          title: "获取失败",
          icon: "none",
        });
      },
    });
  },

  // 添加数据
  addImgsData(openid, imgurl, fileId) {
    const that = this;
    let { swiperList, o_openid } = that.data;
    swiperList.push({
      url: imgurl,
      fileId,
      time: +new Date(),
    });
    wx.showLoading({
      title: "上传中",
      mask: true,
    });
    uimg.where({ _openid: openid }).update({
      data: {
        mySwiper: swiperList,
      },
      success: (res) => {
        if (!o_openid) {
          wx.showToast({
            title: "上传成功",
            icon: "none",
          });
        }
        if (o_openid) {
          uimg.where({ _openid: o_openid }).update({
            data: {
              mySwiper: swiperList,
            },
            success: () => {
              wx.showToast({
                title: "上传成功",
                icon: "none",
              });
            },
            fail: () => {
              wx.showToast({
                title: "出错了",
                icon: "none",
              });
            },
            complete: () => {
              wx.hideLoading();
              that.getImgsData(openid);
            },
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: "出错了",
          icon: "none",
        });
      },
      complete: () => {
        wx.hideLoading();
        if (!o_openid) {
          that.getImgsData(openid);
        }
      },
    });
  },

  // 编辑轮播图
  editSwiper() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        wx.showLoading({
          title: "上传中",
        });
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0];
        that.uploadImage(tempFilePaths);
      },
    });
    // wx.showModal({
    //   title: "编辑封面",
    //   content: "确定要上传自定义封面吗？",
    //   confirmColor: "#a5646d",
    //   success: (result) => {
    //     if (result.confirm) {

    //     }
    //   },
    //   fail: () => { },
    //   complete: () => { },
    // });
  },

  // 上传到云储存
  uploadImage(fileURL) {
    var that = this;
    wx.showLoading({
      title: "上传中请稍等",
      mask: true,
    });
    wx.cloud.uploadFile({
      cloudPath: "swiper/swiper" + new Date().getTime() + ".png", // 上传至云端的路径
      filePath: fileURL, // 小程序临时文件路径
      success: (res) => {
        //获取图片的http路径，准备添加到数据库中
        // console.log(res.fileID);
        that.addImagePath(res.fileID);
        that.setData({
          fileID: res.fileID,
        });
      },
      fail: () => {
        that.setData({
          upLoadDisabled: false,
        });
        wx.hideLoading();
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
    });
  },

  // 获取图片上传后的url路径
  addImagePath(fileId) {
    // console.log(fileId);
    const openid = wx.getStorageSync("openid");

    var that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileId],
      success: (res) => {
        const url = res.fileList[0].tempFileURL;
        that.addImgsData(openid, url, fileId);
      },
      fail: () => {
        that.setData({
          upLoadDisabled: false,
        });
        wx.hideLoading();
        wx.showToast({
          title: "上传失败",
          icon: "error",
        });
      },
    });
  },

  // 删除
  delimg(e) {
    const that = this;
    let { swiperList, openid, o_openid } = that.data;
    const { time, fileid } = e.currentTarget.dataset;
    wx.showModal({
      title: "确认删除",
      content: "确认要删除该轮播封面嘛？",
      success: (result) => {
        if (result.confirm) {
          swiperList = swiperList.filter((i) => i.time != time);
          uimg.where({ _openid: openid }).update({
            data: {
              mySwiper: swiperList,
            },
            success: function (res) {
              if (!o_openid) {
                wx.showToast({
                  title: "删除成功",
                  icon: "success",
                });

                wx.cloud.deleteFile({
                  fileList: [fileid],
                  success(res) {
                    console.log(res, "删除文件");
                  },
                  fail(err) {
                    console.log(err);
                  },
                });
              }
              if (o_openid) {
                uimg.where({ _openid: o_openid }).update({
                  data: {
                    mySwiper: swiperList,
                  },
                  success: () => {
                    wx.showToast({
                      title: "删除成功",
                      icon: "success",
                    });

                    wx.cloud.deleteFile({
                      fileList: [fileid],
                      success(res) {
                        console.log(res, "删除文件");
                      },
                      fail(err) {
                        console.log(err);
                      },
                    });
                  },
                  fail: () => {
                    wx.showToast({
                      title: "删除失败",
                      icon: "none",
                    });
                  },
                  complete: () => {
                    that.getImgsData(openid);
                  },
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: "删除失败",
                icon: "none",
              });
            },
            complete: () => {
              if (!o_openid) {
                that.getImgsData(openid);
              }
            },
          });
        }
      },
    });
  },

  sureNotice() {
    this.setData({
      showNotice: false,
    });
    wx.setStorageSync("showNotice", false);
  },

  //options(Object)
  onLoad(options) { },
  onReady: function () { },
  onShow: function () {
    const { myInterval } = this.data;
    const openid = wx.getStorageSync("openid");
    const o_openid = wx.getStorageSync("o_openid");
    const showNotice = wx.getStorageSync("showNotice");
    clearInterval(myInterval);

    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,
        theme: app.globalData.theme,
      });
    }
    this.setData({
      theme: app.globalData.theme,
      o_openid,
    });
    const { theme } = this.data;
    if (theme == 1) {
      wx.setTabBarStyle({
        backgroundColor: "#a5646d",
      });
    } else if (theme == 2) {
      wx.setTabBarStyle({
        backgroundColor: "#1a1a1a",
      });
    } else if (theme == 3) {
      wx.setTabBarStyle({
        backgroundColor: "#86C6F6",
      });
    } else if (theme == 4) {
      wx.setTabBarStyle({
        backgroundColor: "#85a4cd",
      });
    }
    this.getLoveTime(openid);
    this.getImgsData(openid);
    this.setData({
      theme: app.globalData.theme,
      showNotice: showNotice == "" ? true : showNotice,
    });
  },
  onHide: function () {
    let { myInterval } = this.data;
    clearInterval(myInterval);
  },
  onUnload: function () { },
  onPullDownRefresh() { },
  onReachBottom: function () { },
  onShareAppMessage: function () { },
  onPageScroll: function () { },
  onTabItemTap: function (item) { },
});
